 /*
 * AreaOfInterestDAO.java
 *
 * Created on February 13, 2007
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author craig marshall
 */
package finalintex2web;
import java.util.*;
import java.io.*;
import java.sql.*;

/**
 * database access object for area of interests
 */
public class AreaOfInterestDAO {
    
    
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static AreaOfInterestDAO instance = null;
    
    /** Creates a new instance of RSSFeedDAO */
    private AreaOfInterestDAO() {
    }
    
    /**
     * 
     * @return 
     */
    public static synchronized AreaOfInterestDAO getInstance() {
        if (instance == null) {
            instance = new AreaOfInterestDAO();
        }
        return instance;
    }
    
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * 
     * @return 
     */
    public AreaOfInterestBO create() {
        String id = GUID.generate();
        AreaOfInterestBO aoi = new AreaOfInterestBO(id);
        Cache c = Cache.getInstance();
        c.put(aoi.getId(), aoi);
        return aoi;
    }
    
    
    /////////////////////////////////////
    ///   READ
    /** 
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized AreaOfInterestBO read(String id) throws DataException, ConnectionPoolException {
        if(Cache.getInstance().containsKey(id)){
            AreaOfInterestBO aoi = (AreaOfInterestBO)Cache.getInstance().get(id);
            return aoi;
        }
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            AreaOfInterestBO aoi = read(id,conn);
            ConnectionPool.getInstance().release(conn);
            return aoi;
        }catch (SQLException e) {
            // rollback
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
       
    }
    
    /** 
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection AreaOfInterestBOs or SQLExceptions.
     */
    public synchronized AreaOfInterestBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {
            if(Cache.getInstance().containsKey(id)){
            AreaOfInterestBO aoi = (AreaOfInterestBO)Cache.getInstance().get(id);
            return aoi;
            } 
                
                   
           PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AreaOfInterest WHERE id=?");
           stmt.setString(1,id);
           ResultSet rs =  stmt.executeQuery();
           
           ConnectionPool.getInstance().release(conn);
            
            if (rs.next()) {
                AreaOfInterestBO aoi = new AreaOfInterestBO(id);
                aoi.setDescription(rs.getString("description"));
                Cache.getInstance().put(id,aoi);
               // MemberBO m = MemberDAO.getInstance().read(rs.getString("memberid"));
               // aoi.setMembership(m);
                aoi.setIndb(true);
                //Cache.getInstance().put(id,aoi);
                stmt.close();
                return aoi;

            }else{
                throw new DataException("AreaOfInterestBO was not found in the database.");

            }
            
            
    }
        
    
    
    //////////////////////////////////
    ///   UPDATE
    
    /** 
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an AreaOfInterestBO
     * into the database.
     */
    public synchronized void save(AreaOfInterestBO aoi) throws DataException,ConnectionPoolException {
        
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            save(aoi,conn);
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id=" + aoi.getId(), e);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /** 
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection AreaOfInterestBOs or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the AreaOfInterestDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  AreaOfInterestBO needs to be inserted or updated.
     */
     synchronized void save(AreaOfInterestBO aoi, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // check the dirty flag in the AreaOfInterestBO.  if it is dirty, 
        // run update or insert
        if (aoi.isDirty()) {
            if (aoi.isIndb()) {
                update(aoi, conn);
            }else{
                insert(aoi, conn);
            }
            aoi.setDirty(false);
        }
        
        // call save(bo, conn) on any subAreaOfInterestBOs (like AreaOfInterestDAO to MembershipDAO)
        // touch the cache for the AreaOfInterestBO
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(AreaOfInterestBO aoi, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        PreparedStatement stmt = conn.prepareStatement("UPDATE AreaOfInterest SET description=? WHERE id=? ");
        stmt.setString(1,aoi.getDescription());
        stmt.setString(2,aoi.getId());
        stmt.execute();
        stmt.close();
        ConnectionPool.getInstance().release(conn);
    }
     
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(AreaOfInterestBO aoi, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // do the insert SQL statement
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO AreaOfInterest (description,id) VALUES ( ?,?)");
        stmt.setString(1,aoi.getDescription());
        stmt.setString(2,aoi.getId());
        stmt.execute();
        stmt.close();
        // tell the AreaOfInterestBO that it's now in the db (so we call update next time not insert)
        aoi.setIndb(true);
        ConnectionPool.getInstance().release(conn);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // We are not implementing this feature in this class to help preserve data intergity.

    //////////////////////////////
    ///  SEARCH methods
    
    /**
     * 
     * @throws intex2.DataException 
     * @throws intex2.ConnectionPoolException 
     * @throws java.sql.SQLException 
     * @return 
     */
     public ArrayList<List> getAll() throws DataException,ConnectionPoolException,SQLException {
        
         ArrayList<List> table = new ArrayList<List>();
         
         Connection conn = ConnectionPool.getInstance().get();
         PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AreaOfInterest" );
         ResultSet rs = stmt.executeQuery();
         
        while(rs.next()){
            ArrayList<String> row = new ArrayList<String>();
            row.add(rs.getString("id")); 
            row.add(rs.getString("description"));  
            table.add(row);
        }
        
        ConnectionPool.getInstance().release(conn);
        
        return table;
    }
    
  //  public List<AreaOfInterestBO> getByName(String fname, String lname) throws DataException {
        // similar to getAll
        
    //}
    
    //public List<AreaOfInterestBO> getByPhone(String phone) throws DataException {
        // similar to getByPhone
    //}
}